package com.suitsoft.bdms.commos;

import java.lang.reflect.Method;
import java.util.Date;

import org.apache.struts2.ServletActionContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.Interceptor;
import com.suitsoft.logback.H2Logback;
import com.suitsoft.logback.LogbackData;

/**
 * 应用程序日志拦截器.
 * 
 * log_date操作日期
 * log_time操作时间
 * log_userId操作人id
 * log_ip 登录ip
 * log_content 操作详细内容 （一级模块名-二级模块名-三级模块名：动作（查询、新增、修改、删除）：详细内容（查询条件或操作条件））
 * log_sql 操作的sql语句
 * log_memo 操作备注 
 * 
 * @author waynett
 */
@SuppressWarnings("serial")
public class LoggingInterceptor implements Interceptor {

	/** 日志输出对象 */
	protected final Logger logger = LoggerFactory.getLogger(getClass());

	private H2Logback logback = null;

	/**
	 * 初始化方法.
	 */
	@Override
	public void init() {
		logback = new H2Logback();
		logback.init();
		
		AppConfig.getInstance().setLogback(logback);
	}

/** 原有版本	
	@Override 
	public String intercept(ActionInvocation actionInvocation) throws Exception {
		@SuppressWarnings("unused")
		StringBuffer buffer = new StringBuffer();

		// 取得Action
		Object action = actionInvocation.getAction();
		Class<?> clazz = action.getClass();

		// 重置内容
		Field field = null;
		try {
			field = clazz.getDeclaredField("logbackData");
		} catch (NoSuchFieldException e) {
		}

		LogbackData logbackData = null;

		if (null != field) {
			logbackData = new LogbackData();

			field.setAccessible(true);
			field.set(action, null);

			// 取得当前操作员的姓名
			Object obj = UserHolder.getLoginUser();
			String username = "未知";
			if (obj instanceof LoginUser) {
				LoginUser loginUser = (LoginUser) obj;
				if (loginUser != null) {
					username = loginUser.getDisplayName();
				}
			}

			// 日期时间
			logbackData.setOpDate(new Date());
			// 操作人
			logbackData.setOperator(username);

			// 登陆IP
			String addr = ServletActionContext.getRequest().getRemoteAddr();
			logbackData.setIp(addr);

			// 位置
			String method = actionInvocation.getProxy().getMethod();
			Map<String,String> lobConfig = AppConfig.getInstance().getLogConfig();
			logbackData.setResource(lobConfig.get(clazz.getName() + "." + method));
		}

		String result = actionInvocation.invoke();

		if (null != field) {
			Object content = field.get(action);
			if (null != content) {
				logbackData.setContent(content.toString());
			}

			logback.log(logbackData);
		}

		return result;
	}
*/
	
	@Override
	public String intercept(ActionInvocation actionInvocation) throws Exception {
		
		LogbackData logbackData = null;
		
		// 取得Action
		Object action = actionInvocation.getAction();
		String methodName = actionInvocation.getProxy().getMethod();
		Class<?> clazz = action.getClass();
		
		//获取方法对象
		Method method = clazz.getMethod(methodName);
		//判断是否有注解
		boolean hasAnnotation = method.isAnnotationPresent(LogAnnotation.class);
		if (hasAnnotation) {
			
			logbackData = new LogbackData();
			
			LogAnnotation annotation = method.getAnnotation(LogAnnotation.class);
	   		String methodDescp = annotation.log();
	   		//方法
	   		logger.debug(methodDescp);
	   		
	   		Object obj = UserHolder.getLoginUser();
	   		String username = "未知";
			if (obj instanceof LoginUser) {
				LoginUser loginUser = (LoginUser) obj;
				if (loginUser != null) {
					username = loginUser.getName();
				}
			}
			//登陆用户
			logger.debug(username);
			// 登陆IP
			String addr = ServletActionContext.getRequest().getRemoteAddr();
			//IP
			logger.debug(addr);
			
			
			// 日期时间
			logbackData.setOpDate(new Date());
			//登陆用户名
			logbackData.setOperator(username);
			//IP
			logbackData.setIp(addr);
			//操作内容
			logbackData.setContent(methodDescp);
			logbackData.setResource(methodDescp);
			logback.log(logbackData);
			
		}
		return actionInvocation.invoke();
	}
	
	
	/**
	 * 销毁方法.
	 */
	@Override
	public void destroy() {
		if (null != logback) {
			logback.destory();
		}
	}
}
